package com.blackcat.http;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

import java.io.*;
import java.util.Base64;

/**
 * 描述 : HttpClient访问restApi获取数据带用户名和密码的认证
 * @author : blackcat
 * @date : 2022/3/24 10:38
*/
@Component
public class Runner implements ApplicationRunner {

	@Override
	public void run(ApplicationArguments args) {
//		simple();
		postByCredential();
	}

	private void simple(){
		CloseableHttpClient client = HttpClients.createDefault();
		String url="https://www.baidu.com";
		HttpGet get=new HttpGet(url);
		try {
			CloseableHttpResponse execute = client.execute(get);
			HttpEntity entity = execute.getEntity();
			InputStream in = entity.getContent();
			StringBuilder builder=new StringBuilder();
			BufferedReader bufreader =new BufferedReader(new InputStreamReader(in));
			for (String temp=bufreader.readLine();temp!=null;temp= bufreader.readLine()) {
				builder.append(temp);
			}
			System.out.println(builder.toString());
		} catch (ClientProtocolException e) {
			throw new RuntimeException(e);
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
	}



	public void postByCredential() {
//	public void postByCredential(String url, String user, String password, String jsonParams) {
		try {
//			"http://39.105.55.147:21000/api/atlas/v2/lineage/5f591c08-2c55-44a6-adb1-5f7909a28ab1";
			// 创建HttpClientBuilder
			HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
			CloseableHttpClient closeableHttpClient = httpClientBuilder.build();
			//restAPi的url路径
			HttpGet httpGet = new HttpGet("http://39.105.55.147:21000/api/atlas/v2/lineage/5f591c08-2c55-44a6-adb1-5f7909a28ab1");
			//添加http头信息 ，认证的信息。
			httpGet.addHeader("Authorization", "Basic " + Base64.getUrlEncoder().encodeToString(("admin" + ":" + "admin").getBytes()));
			String result = "";
			HttpResponse httpResponse = null;
			HttpEntity entity = null;
			try {
				//执行请求
				httpResponse = closeableHttpClient.execute( httpGet);
				//获取到数据
				entity = httpResponse.getEntity();
				if( entity != null ){
					result = EntityUtils.toString(entity);
				}
			} catch (ClientProtocolException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
			// 关闭连接
			closeableHttpClient.close();
			System.out.println("result "+result);
		}catch (Exception e) {
			e.getStackTrace();
		}
	}


}
